package com.javasea.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Before;
import org.junit.Test;

/**
 *@ClassName ShiroTest01
 *@Description TODO
 *@Author longxiaonan@163.com
 *@Date 2021/7/5 0005 18:07
 */
public class ShiroTest03 {

    @Before
    public void init(){
        // 1.根据配置文件创建SecurityManagerFactory
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-test-3.ini");
        // 2.通过工厂获取SecurityManager
        SecurityManager securityManager = factory.getInstance();
        // 3.将SecurityManager绑定到当前运行环境
        SecurityUtils.setSecurityManager(securityManager);
    }

    /** 测试用户认证
     *      认证：用户登陆
     */
    @Test
    public void testLogin(){
        // 4.从当前运行环境中获取subject
        Subject subject = SecurityUtils.getSubject();
        // 5.构造shiro登陆数据
        String username = "zhangsan";
        String password = "123456";
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 6.主体登陆-》realmz域中的认证方法
        subject.login(token);
        // 7.验证用户是否登陆成功
        System.out.println("用户是否登陆成功：" + subject.isAuthenticated());
        // 8.获取登陆成功的数据
        System.out.println(subject.getPrincipal());

        // 登陆成功后，完成授权 -》》》realm域中的授权
        // 授权：检验当前登陆用户是否具有操作权限，是否具有某个角色
        System.out.println(subject.hasRole("role1"));
        System.out.println(subject.isPermitted("user:save"));
    }

}
